##
from random import randint
from time import time, sleep


# def download_task(filename):
#     print('开始下载%s...' % filename)
#     time_to_download = randint(5, 10)
#     sleep(time_to_download)
#     print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))


# def main():
#     start = time()
#     download_task('Python从入门到住院.pdf')
#     download_task('Peking Hot.avi')
#     end = time()
#     print('总共耗费了%.2f秒.' % (end - start))
## 多进程操作
from multiprocessing import Process
from os import getpid
from random import randint
from time import time, sleep

# def download_task(filename):
#     print('启动下载进程，进程号[%d].' % getpid())
#     print('开始下载%s...' % filename)
#     time_to_download = randint(5, 10)
#     sleep(time_to_download)
#     print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))
#
# def main():
#     start = time()
#     p1 = Process(target=download_task, args=('Python从入门到住院.pdf', ))
#     p1.start()
#     p2 = Process(target=download_task, args=('Peking Hot.avi', ))
#     p2.start()
#     p1.join()
#     p2.join()
#     end = time()
#     print('总共耗费了%.2f秒.' % (end - start))

##  多线程操作
from random import randint
from threading import Thread
from time import time, sleep

# 1. 用普通直接创建的方法来
# def download(filename):
#     print('开始下载%s...' % filename)
#     time_to_download = randint(1, 5)
#     sleep(time_to_download)
#     print('%s下载完成! 耗费了%d秒' % (filename, time_to_download))
#
#
# def main():
#     start = time()
#     t1 = Thread(target=download, args=('Python从入门到住院.pdf',))
#     t1.start()
#     t2 = Thread(target=download, args=('Peking Hot.avi',))
#     t2.start()
#     t1.join()
#     t2.join()
#     end = time()
#     print('总共耗费了%.3f秒' % (end - start))

## 2. 用继承Thread类的方式实现
# class DownloadTask(Thread):
#
#     def __init__(self, filename):
#         super().__init__()
#         self._filename = filename
#
#     def run(self):
#         print('开始下载%s...' % self._filename)
#         time_to_download = randint(5, 10)
#         sleep(time_to_download)
#         print('%s下载完成! 耗费了%d秒' % (self._filename, time_to_download))
#
#
# def main():
#     start = time()
#     t1 = DownloadTask('Python从入门到住院.pdf')
#     t1.start()
#     t2 = DownloadTask('Peking Hot.avi')
#     t2.start()
#     t1.join()
#     t2.join()
#     end = time()
#     print('总共耗费了%.2f秒.' % (end - start))

# 打印10次 PongPing
from multiprocessing import Process
from time import sleep

counter = 0

def sub_task(string):
    global counter
    while counter < 10:
        print(string, end='', flush=True)
        counter += 1
        sleep(0.01)


def main():
    start = time()
    Process(target=sub_task, args=('Ping',)).start() # 伪  进程间复制counter 不共享 -- 改成Thread就ok了 线程可以共享内存
    Process(target=sub_task, args=('Pong',)).start()
    end = time()
    print('总共耗费了%.2f秒.' % (end - start))


if __name__ == '__main__':
    main()